package com.fenghongzhang.day014;

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Handler;
import android.os.Message;
import android.provider.Telephony;
import android.util.Log;

public class MyObserver extends ContentObserver {

    private Context context;
    private static final String TAG = "MyObserver";

    private Handler handler;
    public MyObserver(Handler handler, Context context) {
        super(handler);
        this.handler = handler;
        this.context = context;
    }

    /**
     * 自动调用这个方法
     * @param selfChange
     */
    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        Log.i(TAG, "onChange: ");
        //读短信
        ContentResolver contentResolver = context.getContentResolver();
        Cursor query = contentResolver.query(Telephony.Sms.CONTENT_URI, null, null, null, null);
        if(query != null){
            //查所有
//            while(query.moveToNext()){
//
//            }
            //查第一条
            query.moveToFirst();
            String string = query.getString(query.getColumnIndex(Telephony.Sms.BODY));
            Log.i(TAG, "onChange: "+string);

            Message obtain = Message.obtain();
            obtain.obj = string;
            handler.sendMessage(obtain);


            query.close();
        }
    }
}
